import { Component } from 'react';
import { connect } from 'dva';
import { get } from 'lodash';
import PropTypes from 'prop-types';
import { Spin, Icon, Modal, Form, Input, Select } from 'antd';

const FormItem = Form.Item;

class UserEditModal extends Component {
  componentDidMount() {
    const { dispatch, editUserId } = this.props;
    dispatch({
      type: 'users/fetch',
      payload: editUserId,
    });
    dispatch({
      type: 'users/fetchRoles',
    });
  }

  handleSubmit = () => {
    const { onOk } = this.props;
    this.props.form.validateFields((err, values) => {
      if (err) {
        return;
      }
      onOk(values);
    });
  };

  render() {
    const { editUserProfile, roles, loadingRoles, onCancel, form } = this.props;
    const { getFieldDecorator } = form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const title = editUserProfile ? '编辑用户' : '创建用户';

    return (
      <Modal
        title={
          <>
            <Icon type="edit" />&nbsp;&nbsp;{title}
          </>
        }
        visible={true}
        onOk={this.handleSubmit}
        onCancel={onCancel}>
        <Form onSubmit={this.okHandler}>
          <FormItem {...formItemLayout} label="姓名">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '姓名是必填项',
                },
              ],
              initialValue: get(editUserProfile, 'name', null),
            })(<Input placeholder="请填写姓名" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="手机号">
            {getFieldDecorator('mobile', {
              rules: [
                {
                  required: true,
                  message: '手机号是必填项',
                },
              ],
              initialValue: get(editUserProfile, 'mobile', null),
            })(<Input placeholder="请填写手机号" />)}
          </FormItem>

          {!editUserProfile && (
            <FormItem {...formItemLayout} label="密码">
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: '密码是必填项',
                  },
                ],
                initialValue: get(editUserProfile, 'password', null),
              })(<Input type="password" placeholder="请填写密码" />)}
            </FormItem>
          )}

          <FormItem {...formItemLayout} label="角色">
            {getFieldDecorator('roleId', {
              rules: [
                {
                  required: true,
                  message: '角色是必填项',
                },
              ],
              initialValue: get(editUserProfile, 'roleId', null),
            })(
              loadingRoles ? (
                <Spin size="small" spinning={true} />
              ) : (
                <Select
                  showSearch={true}
                  placeholder="请分配用户角色"
                  optionFilterProp="children"
                  filterOption={(input, option) => {
                    return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  }}>
                  {roles.map(item => {
                    return (
                      <Select.Option key={item.id} value={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              )
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}
if (process.env.UMI_ENV !== 'prod') {
  UserEditModal.propTypes = {
    dispatch: PropTypes.func.isRequired,
    form: PropTypes.object.isRequired,
    onOk: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    roles: PropTypes.array.isRequired,
    editUserId: PropTypes.number.isRequired,
    editUserProfile: PropTypes.any,
    loadingRoles: PropTypes.bool.isRequired,
  };
}

UserEditModal.defaultProps = {
  dispatch: () => {},
  onOk: () => {},
  onCancel: () => {},
  form: {},
  editUserId: 0,
  editUserProfile: null,
  roles: [],
  loadingRoles: false,
};

function mapStateToProps({ users, loading }, ownProps) {
  const { onOk, onCancel, editUserId } = ownProps;
  const { roles, profile: editUserProfile } = users;

  return {
    onOk,
    onCancel,
    roles,
    editUserId,
    editUserProfile,
    loadingRoles: loading.effects['users/fetchRoles'],
  };
}

export default connect(mapStateToProps)(Form.create()(UserEditModal));
